import { ENV } from '../.env.js'
import { getDict, payGetToken, payGetTicket, getOpenId, getUserInfo, saveInviteCode } from '../api/index.js'
var jWeixin = require('jweixin-module')

export function formatTime(time) {
  if(!time) {
    return ''
  }
	// 先把传参毫秒转化为new Date()
	const dt = new Date(time)
	const y = dt.getFullYear()
	// 月份是从0开始,需要+1。  +''是把数字转化为字符串,padStart(2,'0')是把字符串设置为2位数,不足2位则在开头加'0'
	const m = (dt.getMonth() + 1 + '').padStart(2, '0')
	const d = (dt.getDate() + '').padStart(2, '0')
	const hh = (dt.getHours() + '').padStart(2, '0')
	const mm = (dt.getMinutes() + '').padStart(2, '0')
	const ss = (dt.getSeconds() + '').padStart(2, '0')
	return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
}

export function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/** 
 * 时间戳转化为年 月 日 时 分 秒 
 * number: 传入时间戳 
 * format：返回格式，支持自定义，但参数必须与formateArr里保持一致 
*/
export function formatTimeTwo(number, format) {

  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  var returnArr = [];

  var date = new Date(number);
  returnArr.push(date.getFullYear());
  returnArr.push(formatNumber(date.getMonth() + 1));
  returnArr.push(formatNumber(date.getDate()));

  returnArr.push(formatNumber(date.getHours()));
  returnArr.push(formatNumber(date.getMinutes()));
  returnArr.push(formatNumber(date.getSeconds()));

  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
}

// 判断是不是对象
export function isBoj(obj) {
	return Object.prototype.toString.call(obj) === '[object Object]'
}

// 判断是不是空对象
export function isObjectNonEmpty(obj) {
  if(obj == null) return false;
  for(let key in obj) {
    console.log(key, obj[key]);
    if(obj[key]) { // 确保是对象自身的属性
      return true;
    }
  }
  return false;
}

// 判断是不是数组
export function isArrayFn(value){
	if(typeof Array.isArray === "function") {
		return Array.isArray(value);
	} else {
		return Object.prototype.toString.call(value) === "[object Array]";
	}
}

// 判断 手机号
export function phoneReg(phone) {
	var myreg = /^[1][3-9][0-9]{9}$/;
	if(!myreg.test(phone)) {
		uni.showToast({
			icon: 'none',
			title: '请输入正确的手机号'
		})
	}
	return myreg.test(phone)
}

//防抖
export function debounce(fn, wait = 500) {
	var timer = null;
	return function() {
		var context = this
		var args = arguments
		if (timer) {
			clearTimeout(timer);
			timer = null;
		}
		timer = setTimeout(function() {
			fn.apply(context, args)
		}, wait)
	}
}

// 节流 默认3000毫秒
export function throttleFunc(func, marginTime) {
	if (marginTime == undefined || marginTime == null) {
		marginTime = 0
	}
	let lastTime = null
	return async function() {
		let currentTime = +new Date()
		if (currentTime - lastTime > marginTime || !lastTime) {
			await func.apply(this, arguments)
			lastTime = currentTime
		}
	}
}

// 获取数据字典
export function getDicts(type=[], that) {
	return new Promise((resolve, reject) => {
    const dicts = uni.getStorageSync('dicts') || {}
    type.forEach(async (v, i) => {
      if(dicts[v]) {
        that.dict[v] = dicts[v]
        resolve()
      } else {
        const res = await getDict(v)
        that.dict[v] = res.data.map(v => {
          return { value: v.dictValue, lable: v.dictLabel, remark: v.remark }
        })
        dicts[v] = res.data.map(v => {
          return { value: v.dictValue, lable: v.dictLabel, remark: v.remark }
        })
        uni.setStorageSync('dicts', dicts)
        if(i == type.length - 1) {
          resolve()
        }
      }
    })
  })
}

// 上传文件
export function uploadFile(size=10) {
	return new Promise((resolve, reject) => {
		wx.chooseMessageFile({
			count: 1,
			type: 'file',
			// extension: ['doc','docx','pdf'],
			success (res) {
				const tempFile = res.tempFiles[0]
        const fileExtension = tempFile.name.substr(tempFile.name.lastIndexOf('.') + 1);
        if(!['doc','docx','pdf','DOC','DOCX','PDF'].some(v => v == fileExtension)) {
          uni.showToast({
						icon: 'none',
						title: `请选择doc、docx、pdf类型文件`
					})
          setTimeout(() => {
            resolve({ code: 202 })
          }, 1000)
          return
        }
				if(tempFile.size/1024/1024>size) {
					uni.showToast({
						icon: 'none',
						title: `文件大于${size}MB请重新选择`
					})
          setTimeout(() => {
            resolve({ code: 202 })
          }, 1000)
          return
				}
				uni.showLoading({ mask: true })
				wx.uploadFile({
					url:  ENV.BASE_API + '/file/uploadOSS',
					filePath: tempFile.path,
          timeout: 1000 * 60 * 5,
					name: 'file',
					header: {
						[ENV.HEAD]: uni.getStorageSync('token') || '',
					},
					formData: {
						fileName: tempFile.name
					},
					success (res){
						uni.hideLoading({})
						// #ifdef APP-PLUS || H5
						var data = res.data
						// #endif
						// #ifdef MP-WEIXIN
						var data = JSON.parse((res.data))
						// #endif
            data.newFileName = tempFile.name
						resolve(data)
					},
					fail(err) {
            uni.hideLoading();
            console.log(err);
            uni.showToast({
              icon: 'none',
              title: `文件上传失败`
            })
            setTimeout(() => {
              resolve({ code: 202 })
            }, 1000)
					},
				})
			},
			fail() {
				uni.hideLoading();
        uni.showToast({
          icon: 'none',
          title: `文件选择失败`
        })
        setTimeout(() => {
          resolve({ code: 202 })
        }, 1000)
			},
		})
	})
}

// 上传图片
export function uploadImage(tempFile) {
	return new Promise((resolve, reject) => {
    uni.showLoading({ mask: true })
    wx.uploadFile({
      url:  ENV.BASE_API + '/file/uploadOSS',
      filePath: tempFile.url,
      name: 'file',
      header: {
        [ENV.HEAD]: uni.getStorageSync('token') || '',
      },
      formData: {
      },
      success (res){
        uni.hideLoading({})
        // #ifdef APP-PLUS || H5
        var data = JSON.parse((res.data))
        // #endif
        // #ifdef MP-WEIXIN
        var data = JSON.parse((res.data))
        // #endif
        resolve(data)
      },
      fail(err) {
				uni.hideLoading();
				console.log(err);
				resolve({ code: 202 })
      },
    })
	})
}

// 下载文件
export function downloadFile(fileUrl) {
	return new Promise((resolve, reject) => {
		uni.showLoading({ mask: true })
		uni.downloadFile({
			url: fileUrl,
			success: (downloadRes) => {
				if (downloadRes.statusCode === 200) {
					// 文件临时路径
					const tempFilePath = downloadRes.tempFilePath;
					//打开文件
					uni.openDocument({
						filePath: tempFilePath,
						showMenu: true,
						success: () => {
							uni.showToast({
								icon: 'none',
								title: '导出成功！',
							})
						},
						fail: (err) => {
							uni.showToast({
								icon: 'none',
								title: '文件已下载，但无法打开',
							})
						}
					});
				} else {
					uni.showToast({
						icon: 'none',
						title: '下载失败，请重试',
					})
				}
			},
			fail: (err) => {
				uni.showToast({
					title: '下载失败，请重试',
				})
			},
			complete: () => {
				uni.hideLoading();
			}
		});
  })
}

// 判断浏览器环境
export function isWeChatBrowser() {
	var ua = window.navigator.userAgent.toLowerCase()
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
			return true // 微信中打开
	} else {
			return false // 普通浏览器中打开
	}
}

// 公众号分享
export function wxShare(shareInfo= {}, f = false) {
  const sharemgurl = 'https://oss.tonghuajiankang.com/upload/2025/10/30/1761795012805_776.png'
	if (isWeChatBrowser()) {
		uni.showLoading()
		payGetToken().then((res) => {
			const url = uni.getSystemInfoSync().platform === 'ios' ? uni.getStorageSync('url').split('#')[0] : window.location.href //在你传给后端url获取返回参数配置wx.config前，加动态判断
      payGetTicket({ accessToken: res, urll: url }).then((res) => {
				uni.hideLoading()
				jWeixin.config({
					// debug: true,
					appId: ENV.APP_ID,
					timestamp: res.data.timestamp, // 当前时间戳（10位整数）
					nonceStr: res.data.noncestr, // 随机字符串（16~32位字母+数字）
					signature: res.data.signature, // SHA1签名（40位十六进制）
					jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData'],
				})
		
				jWeixin.ready(() => {
					jWeixin.updateTimelineShareData({
						title: shareInfo.title,
						link: shareInfo.link,
						imgUrl: shareInfo.imgUrl || sharemgurl,
						success: () => {
						},
					})
					// 分享给朋友
					jWeixin.updateAppMessageShareData({
						title: shareInfo.title,
						link: shareInfo.link,
						desc: shareInfo.desc || '',
						imgUrl: shareInfo.imgUrl || sharemgurl,
						success: () => {
							console.log('wxShare分享配置成功', res);
						},
					})
				})
		
				jWeixin.error((res) => {
					console.log('wxShare分享配置失败', res);
				})
			})
		})
  } else {
    if(f) {
      uni.setClipboardData({
        data: shareInfo.link,
        success: function () {
          uni.showToast({
            title: '复制成功，快去分享吧',
            icon: 'none'
          })
        },
      });
    }
  }
}

// 默认分享
export function defaultShare(shareInfo= {}) {
  const sharemgurl = 'https://oss.tonghuajiankang.com/upload/2025/10/30/1761795012805_776.png'
	if (isWeChatBrowser()) {
		payGetToken().then((res) => {
			const url = uni.getSystemInfoSync().platform === 'ios' ? uni.getStorageSync('url').split('#')[0] : window.location.href //在你传给后端url获取返回参数配置wx.config前，加动态判断
      payGetTicket({ accessToken: res, urll: url }).then((res) => {
				jWeixin.config({
					// debug: true,
					appId: ENV.APP_ID,
					timestamp: res.data.timestamp, // 当前时间戳（10位整数）
					nonceStr: res.data.noncestr, // 随机字符串（16~32位字母+数字）
					signature: res.data.signature, // SHA1签名（40位十六进制）
					jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData'],
				})
		
				jWeixin.ready(() => {
					const userInfo = uni.getStorageSync('userInfo')
					let url = ENV.HTTP_URL
					if(userInfo && userInfo.userId) {
						url = ENV.HTTP_URL + '?invitationCode=' + userInfo.invitationCode
					}
					jWeixin.updateTimelineShareData({
						title: '果然年代',
						link: url,
						imgUrl: sharemgurl,
						success: () => {
						},
					})
					// 分享给朋友
					jWeixin.updateAppMessageShareData({
						title: '果然年代',
						link: url,
						desc: '',
						imgUrl: sharemgurl,
						success: () => {
							console.log('defaultShare分享配置成功', res);
						},
					})
				})
		
				jWeixin.error((res) => {
					console.log('defaultShare分享配置失败', res);
				})
			}).catch(err => {
				console.log(err);
			})
		}).catch(err => {
			console.log(err);
		})
  } else {
  }
}

export async function utilWxLogin() {
	if(!uni.getStorageSync('token')) {
		// 判断是否是微信浏览器
		if (isWeChatBrowser()) {
			// 获取微信用户信息
			let url = ''
			if(ENV.BASE_API == '/api') {
				url = ENV.HTTP_URL
			} else {
				url = window.location.href
			}
			if (url.indexOf('code=') == -1) {
				uni.showModal({
					title: '提示',
					content: '为了提供完整的服务,我们需要您同意我们获取微信昵称和头像',
					confirmText: '同意授权',
					success: async function (res) {
						if (res.confirm) {
							const appid = ENV.APP_ID
							let currentURL = encodeURIComponent(window.location.origin)
							let redirect_uri = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${currentURL}&response_type=code&scope=snsapi_userinfo&forcePopup=true&state=STATE#wechat_redirect`
							window.location.href = redirect_uri
						} else if (res.cancel) {
							uni.setStorageSync('noLogin', '果然年代')
							uni.reLaunch({
								url: '/pages/index/index'
							})
						}
					}
				});
			} else {
				let url = window.location.href
				let code = url.split('code=')[1].split('&')[0]
				uni.showLoading({ mask: true })
				await	getOpenId({ code: code }).then(async (res) => {
					const token = 'Bearer ' + res.data.access_token
					uni.setStorageSync('token', token)
					defaultShare()
					await getUserInfo({}).then(async res => {
						uni.hideLoading()
						uni.setStorageSync('userInfo', {...res.user, roles: res.roles})
						if(uni.getStorageSync('invitationCode') && !res.user.invitationName) {
							const parameter = {
								userId: res.user.userId,
								invitationCode: uni.getStorageSync('invitationCode'),
							}
							saveInviteCode(parameter).catch(err => {
								console.log(err);
							});
							uni.removeStorageSync('invitationCode')
						}
						console.log(uni.getStorageSync('invitationUrl'));
						if(uni.getStorageSync('invitationUrl')) {
							uni.reLaunch({
								url: uni.getStorageSync('invitationUrl')
							})
						} else if(res.user.phonenumber) {
							uni.showToast({
								icon: 'none',
								title: `登录成功`
							})
							setTimeout(() => {
								uni.reLaunch({
									url: '/pages/index/index'
								})
							}, 1000)
						} else {
							uni.showToast({
								icon: 'none',
								title: `请绑定手机号`
							})
							setTimeout(() => {
								uni.reLaunch({
									url: '/pages/userInfo/userPhone'
								})
							}, 1000)
						}
					})
				}).catch(err => {
					console.log(err);
				})
			}
		}
	}
}